//
//  HYMyBookingSwitchView.m
//  Booking
//
//  Created by Maybe_文仔 on 2018/7/11.
//  Copyright © 2018年 Duntech. All rights reserved.
//

#import "HYMyBookingSwitchView.h"

@interface HYMyBookingSwitchView(){
    NSArray *_itemTitles;
    UIButton *_selectedBtn;
}
@end

@implementation HYMyBookingSwitchView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
    }
    return self;
}

-(instancetype)initWithItemTitles:(NSArray *)itemTitles{
    if (self = [super init]) {
        _itemTitles = itemTitles;
        
        [self setupSubviews];
    }
    return self;
}

-(void)setupSubviews{
    self.layerCornerRadius = 8.0;
    self.layerBorderColor = KAPP_THEME_COLOR;
    self.layerBorderWidth = 1.0;
    
    if (_itemTitles.count > 0) {
        NSInteger i = 0;
        for (id obj in _itemTitles) {
            if ([obj isKindOfClass:[NSString class]]) {
                NSString *objStr = (NSString *)obj;
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                [self addSubview:btn];
                btn.backgroundColor = [UIColor whiteColor];
                [btn setTitle:objStr forState:UIControlStateNormal];
                [btn setTitleColor:KAPP_THEME_COLOR forState:UIControlStateNormal];
                [btn setTitleColor:KAPP_THEME_COLOR forState:UIControlStateSelected];
                [btn setBackgroundColor:KAPP_THEME_COLOR];
                btn.titleLabel.font = KFitFont(14);
                i = i + 1;
                btn.tag = i;
                if (i == 2) {
                   _selectedBtn = btn;
                }
                [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
                btn.adjustsImageWhenDisabled = NO;
                btn.adjustsImageWhenHighlighted = NO;
            }
        }
    }
}

- (void)btnClick:(UIButton *)btn {
    _selectedBtn.backgroundColor = [UIColor whiteColor];
    btn.backgroundColor =  KAPP_THEME_COLOR;
    
    [_selectedBtn setTitleColor:KAPP_THEME_COLOR forState:(UIControlStateNormal)];
    [btn setTitleColor:KAPP_WHITE_COLOR forState:(UIControlStateSelected)];
    
    _selectedBtn.selected = NO;
    btn.selected = YES;
    
    _selectedBtn = btn;
    NSString *title = btn.currentTitle;
    if (self.NHCustomSegmentViewBtnClickHandle) {
        self.NHCustomSegmentViewBtnClickHandle(self, title, btn.tag - 1);
    }
}

- (void)clickDefault {
    if (_itemTitles.count == 0) {
        return ;
    }
    [self btnClick:(UIButton *)[self viewWithTag:1]];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    if (_itemTitles.count > 0) {
        CGFloat btnW = self.width / _itemTitles.count;
        for (int i = 0 ; i < _itemTitles.count; i++) {
            UIButton *btn = (UIButton *)[self viewWithTag:i + 1];
            btn.frame = CGRectMake(btnW * i, 0, btnW, self.height);
        }
    }
}


@end
